<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class NewsController extends Controller
{

    /**
    *   数据的显示列表
    */
    public function getIndex()
    {
        $res = DB::table('news')->orderBy('id','asc')->paginate(5);

       // var_dump($res);die;

        return view('news/index',['row'=>$res]);

    }
    /**
    *   数据的添加页面
    */
    public function getAdd()
    {
        return view('news/add');
    }

    /**
    *   数据的添加方法
    */
    public function postInsert(Request $request)
    {
        //接受数据
        $res = $request->except('_token');

        //检测上传文件
        if($request->hasFile('pic')){

            //随机名
            $name = md5(rand(10000,99999).time());
            //获取后缀名
            $suffix = $request->file('pic')->getClientOriginalExtension();

            $request->file('pic')->move('./upload/',$name.'.'.$suffix);

            $res['logo'] = '/upload/'.$name.'.'.$suffix;

            unset($res['pic']);

        }

        //插入数据
        DB::table('news')->insert($res);

        //跳转
       return redirect('news/index');
    }

    /**
    *   修改信息页面
    */
    public function getEdit(Request $request)
    {
        //获取id
        $id = $request ->input('id');

       $res = DB::table('news')->where('id',$id)->first();

       return view('news/edit',['row'=>$res]);


    }

    /**
    *   修改数据的方法
    */

    public function postUpdate(Request $request)
    {
        //获取id
        $id = $request->input('id');

        $res = $request->except('_token','id'); 

        DB::table('news')->where('id',$id)->update($res);

        return redirect('news/index');
    }

    /**
    *   数据的删除方法
    */
    public function getDelete(Request $request)
    {
       $id = $request->input('id');

       DB::table('news')->where('id',$id)->delete();

       return redirect('news/index');
    }
}
